import { useLocation } from 'react-router-dom'
import { Breadcrumb } from 'antd'
import routes from '@/router'

type routeType = {
  path: string
  breadcrumbName: string
  element?: JSX.Element
  children?: routeType[]
}

// 递归创建面包屑名称与路径之间的对应关系
const getBreadcrumbNameMap = (routes: routeType[]) => {
  const map = new Map()
  const traverse = (route: routeType) => {
    map.set(route.path, route.breadcrumbName)
    if (route.children) {
      route.children.forEach((item) => {
        traverse(item)
      })
    }
  }
  routes.forEach((item) => {
    traverse(item)
  })
  return map
}
const Comp: React.FC = () => {
  const breadcrumbNameMap = getBreadcrumbNameMap(routes)
  const currentRoute = useLocation()
  const pathSnippets = currentRoute.pathname.split('/').filter((i) => i)

  const extraBreadcrumbItems = pathSnippets.map((_, index) => {
    const url = `/${pathSnippets.slice(0, index + 1).join('/')}`
    return {
      title: breadcrumbNameMap.get(url),
    }
  })

  return (
    <>
      <Breadcrumb
        style={{ margin: '16px 0' }}
        items={extraBreadcrumbItems}
      ></Breadcrumb>
    </>
  )
}

export default Comp
